<template>
  <div class="body fade-show" v-if="!initLoading">
    <div class="goods-list">
      <template v-for="(item, index) in goodsList" :key="index">
        <div class="goods-item">
          <div class="goods-item-detail">
            <image
              :src="item.goods_image"
              class="goods-image"
              mode="aspectFill"
            ></image>
            <div class="goods-right">
              <div class="goods-name">{{ item.goods_name }}</div>
              <div class="goods-rate">
                <rate
                  :current="formData[index]?.rate"
                  @change="rateChange(index, $event)"
                  active="#e72222"
                ></rate>
              </div>
            </div>
          </div>
          <div class="comment-context">
            <textarea
              placeholder="请输入评价内容"
              maxlength="2000"
              v-model="formData[index].content"
            ></textarea>
          </div>
          <!-- 上传 -->
          <div>
            <uploadList :max-count="5" @change="uploadChange(index, $event)"></uploadList>
          </div>
          <div class="anonymous">
            <checkbox
              class="checkbox"
              catchtap="checkChange"
              :data-index="index"
              :checked="formData[index]?.anonymous == 1 ? true : false"
            ></checkbox>
            <text>匿名评论</text>
          </div>
        </div>
      </template>
    </div>

    <div class="save-box fixed">
      <div
        class="save-btn"
        @click="save"
        :style="{ background: DIYTHEME?.host_bg, color: DIYTHEME?.host_color }"
      >
        提交
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { useConfig } from "@/store";
import { onLoad, onShow } from "@dcloudio/uni-app";
import { storeToRefs } from "pinia";
import { ref, getCurrentInstance, onMounted, nextTick } from "vue";
import { getGoodsCommentOrder, createGoodsComment } from "@/api/goods-comment";

import uploadList from "@/components/ui/upload-list/index.vue";
import { uploadCacheImage } from "@/api/common";
import { Result, ResultError } from "@/types";

const { DIYTHEME } = storeToRefs(useConfig());

interface formItemType {
  goods_id: number;
  order_goods_id: number;
  rate: number;
  files: Array<string>;
  content: string;
  anonymous: number;
  imgs: any;
}

const {
  proxy,
  proxy: { $utils },
} = getCurrentInstance() as any;

const orderId = ref<number>(0);

const formData = ref<Array<formItemType>>([]);

const initLoading = ref<boolean>(true);

const goodsList = ref<any>([]);

const toInit = () => {
  getGoodsCommentOrder({
    order_id: orderId.value,
  })
    .then((res: Result) => {
      goodsList.value = res.data.goodsList;
      initLoading.value = false;
      toInitFormData();
    })
    .catch((err: ResultError) => {
      $utils.errorMsg(err);
    });
};

const toInitFormData = () => {
  formData.value = [];
  goodsList.value.forEach((item: any, index: number) => {
    formData.value.push({
      goods_id: item.goods_id,
      order_goods_id: item.id,
      rate: 5,
      files: [],
      content: "",
      anonymous: 0,
      imgs: [],
    });
  });
};

onLoad((options: any) => {
  orderId.value = options.id || 0;
  toInit();
});

const rateChange = (index: number, res: any) => {
  console.log(index, res);
  formData.value[index].rate = res.rate;
};

const uploadChange = (index: number, res: string[]) => {
  formData.value[index].files = res;
};

const saveLoading = ref<boolean>(false);

const save = () => {
  let _formData = formData.value;
  uni.showLoading({
    title: "正在处理...",
    mask: true,
  });

  for (var key in _formData) {
    if (_formData[key].content === "") {
      $utils.errorMsg("请输入评论内容");
      return false;
    }
  }
  // 判断是否重复提交
  if (saveLoading.value === true) {
    return false;
  }
  // // 表单提交按钮设为禁用 (防止重复提交)
  saveLoading.value = true;

  // 统计图片数量
  let imagesLength = 0;
  _formData.forEach((item: formItemType, formIndex: number) => {
    if(item.content !== ""){
      imagesLength += item.files.length
    }
  });

  // 判断是否需要上传图片
  imagesLength > 0
    ? uploadFile(imagesLength, _formData, fromPostCall)
    : fromPostCall(_formData);
};

// form提交执行
const fromPostCall = (_formData: Array<formItemType>) => {
  createGoodsComment({
    order_id: orderId.value,
    formData: JSON.stringify(_formData),
  })
    .then((res: Result) => {
      uni.hideLoading();
      saveLoading.value = false;
      $utils.successMsg(res.message);
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
    })
    .catch((err: ResultError) => {
      $utils.errorMsg(err);
      saveLoading.value = false;
    });
};

// 上传图片
const uploadFile = (
  imagesLength: number,
  _formData: Array<formItemType>,
  callBack: Function
) => {
  let uploaded: any = [];
  // 文件上传
  let i = 0;
  _formData.forEach((item: formItemType, formIndex: number) => {
    if (item.content !== "") {
      item.files.forEach((filePath: string, fileKey: number) => {
        uploadCacheImage(filePath)
          .then((res: Result) => {
            uploaded[fileKey] = res.data;
            i++;
            if (imagesLength === i) {
              // 所有文件上传完成
              _formData[formIndex].imgs = uploaded;
              // 执行回调函数
              callBack && callBack(_formData);
            } else {
              saveLoading.value = false;
            }
          })
          .catch((err: ResultError) => {
            $utils.errorMsg(err);
            saveLoading.value = false;
          });
      });
    }
  });
};
</script>

<style>
page {
  background: var(--base-page);
}
</style>

<style scoped>
.goods-item {
  width: calc(100% - 80rpx);
  margin: 20rpx 20rpx 0;
  padding: 40rpx 20rpx;
  background: #fff;
  border-radius: 10rpx;
}
.goods-item-detail {
  display: flex;
  justify-content: flex-start;
}
.goods-image {
  width: 120rpx;
  height: 120rpx;
}
.goods-right {
  margin-left: 20rpx;
  position: relative;
  width: calc(100% - 180rpx);
}
.goods-name {
  font-size: var(--base-size-default);
  width: 100%;
}
.goods-rate {
  position: absolute;
  left: 0;
  bottom: 20rpx;
  display: flex;
  align-items: center;
}
.goods-rate-text {
  line-height: 55rpx;
  margin-left: 20rpx;
}
.comment-context {
  margin-top: 20rpx;
}
.comment-context textarea {
  background: rgba(0, 0, 0, 0.02);
  width: calc(100% - 40rpx);
  height: 160rpx;
  padding: 20rpx;
  font-size: var(--base-size-default);
  border-radius: var(--base-radius-default);
}
.anonymous {
  display: flex;
  align-items: center;
  margin-top: 30rpx;
}
.anonymous text {
  margin-left: 20rpx;
}

.save-btn {
  width: calc(100% - 40rpx);
  margin: 25rpx auto;
  text-align: center;
  height: 70rpx;
  line-height: 70rpx;
  color: #fff;
  border-radius: 10rpx;
}

.save-box.fixed {
  position: fixed;
  width: 100%;
  height: 120rpx;
  z-index: 9999;
  left: 0rpx;
  bottom: 0rpx;
  background: #fff;
}
</style>